package com.ukefu.webim.util.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.util.HttpClientUtil;
import com.ukefu.webim.util.OnlineUserUtils;
import com.ukefu.webim.util.event.AiMessageOtherProcesser;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.util.server.message.OtherMessage;
import com.ukefu.webim.util.server.message.OtherMessageItem;
import com.ukefu.webim.web.model.AiConfig;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.SystemConfig;
import com.ukefu.webim.web.model.Template;

@Component
public class AiMessageOtherProcesserImpl implements AiMessageOtherProcesser{
	private ObjectMapper objectMapper = new ObjectMapper();
	@SuppressWarnings("unchecked")
	@Override
	public ChatMessage process(ChatMessage message , AiMRoundsProcesserImpl aiMroundsProcesser , AiUser aiUser) {
		ChatMessage retChatMessage = null ;
		try {
			String lastMsg = message.getMessage() ;
			if(!StringUtils.isBlank(message.getMsgtype()) && (message.getMsgtype().equals(UKDataContext.MediaTypeEnum.IMAGE.toString()) || message.getMsgtype().equals(UKDataContext.MediaTypeEnum.VOICE.toString()))) {
				SystemConfig systemConfig = (SystemConfig) CacheHelper.getSystemCacheBean().getCacheObject("systemConfig", UKDataContext.SYSTEM_ORGI);
				if(systemConfig!=null) {
					message.setMessage(systemConfig.getIconstr()+message.getMessage());
				}
			}else if(!StringUtils.isBlank(message.getMessage())){
				message.setMessage(message.getMessage().replaceAll("\n", ""));
			}
			AiConfig aiConfig = AiUtils.initAiConfig(message.getAiid(), message.getOrgi()) ;
			String text = null ;
			Map<String,Object> values = new HashMap<String,Object>();
			values.put("chat", message) ;
			values.put("aiConfig", aiConfig) ;
			values.put("aiuser", aiUser) ;
			values.put("appid", message.getAppid()) ;
			values.put("aiid", aiUser!=null?aiUser.getAiid():message.getAiid()) ;
			if(aiConfig.isOtherlogin()) {
				String result = HttpClientUtil.doPost(UKTools.getTemplet(aiConfig.getOtherurl(), values), values) ;
				Map<String,Object> loginValues = objectMapper.readValue(result, Map.class) ;
				if(loginValues!=null && loginValues.get("access_token")!=null) {
					values.put("access_token", loginValues.get("access_token")) ;		
				}
			}
//			if(!StringUtils.isBlank(message.getMediaid())) {
//				text = "{\"id\":\""+message.getMediaid()+"\" , \"detail\":true}" ;
//			}else 
			{
				String param = "" ;
				if(!StringUtils.isBlank(aiConfig.getOthertempletinput())) {
					Template templet = UKTools.getTemplate(aiConfig.getOthertempletinput()) ;
					param = UKTools.getTemplet(templet.getTemplettext(), values) ;
				}
				String result = HttpClientUtil.doPost(aiConfig.getOtherurl(), param) ;
				if(StringUtils.isNotBlank(result) && !StringUtils.isBlank(aiConfig.getOthertempletoutput()) && !result.equals("error")) {
					Template templet = UKTools.getTemplate(aiConfig.getOthertempletoutput()) ;
					try {
						Map<String,Object> jsonData = null ;
						if(result.trim().matches("[\\s\\S]*?\\[[\\S\\s]*?\\][\\s\\S]*?") && result.trim().startsWith("[")) {
							jsonData = new HashMap<String,Object>();
							JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class,Map.class);
							List<Map<String,Object>> tempData = objectMapper.readValue(result, javaType) ;
							jsonData.put("data", tempData) ;
						}else {
							jsonData = objectMapper.readValue(result, Map.class) ;
						}
						text = UKTools.getTemplet(templet.getTemplettext(), values) ;
					}catch(Exception ex) {
						ex.printStackTrace();
						text = "{\"message\":\"传入的参数错误["+message.getMsgtype()+"]\"}" ;
					}
				}else {
					text = "{\"message\":\""+result + "["+message.getMsgtype()+"]["+message.getMessage()+"]\"}" ;
				}
			}
			
			/**
			 * 以下代码需要在接口调用的时候增加 URL拼接 访问地址
			 */
			if(!StringUtils.isBlank(message.getMessage()) && !message.getMessage().equals(lastMsg)) {
				message.setMessage(lastMsg);
			}
			if(!StringUtils.isBlank(text)){
				OtherMessage otherMessage = objectMapper.readValue(text, OtherMessage.class) ;
				if(otherMessage!=null) {
					retChatMessage = new ChatMessage();
					if(otherMessage.isDetail() && !StringUtils.isBlank(otherMessage.getId())) {
						OtherMessageItem otherMessageItem = OnlineUserUtils.suggestdetail(aiUser,aiConfig , otherMessage.getId(), message.getOrgi() , message.getAppid(), null) ;
						if(otherMessageItem!=null) {
							if(otherMessageItem!=null && !StringUtils.isBlank(otherMessageItem.getContent())) {
								otherMessage.setMessage(otherMessageItem.getContent());
							}
							retChatMessage.setHeadimgurl(otherMessageItem.getHeadimg());
							if(UKDataContext.MediaTypeEnum.NEWS.toString().equals(otherMessageItem.getType())) {
								retChatMessage.setBustype(UKDataContext.MediaTypeEnum.NEWS.toString());
							}else if(UKDataContext.MediaTypeEnum.VOICE.toString().equals(otherMessageItem.getType())) {
								otherMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
								retChatMessage.setBustype(UKDataContext.MediaTypeEnum.VOICE.toString());
								retChatMessage.setDuration(otherMessageItem.getDuration());
							}else {
								retChatMessage.setBustype(UKDataContext.MediaTypeEnum.TEXT.toString());
							}
							retChatMessage.setMatchtype(UKDataContext.AiMatchType.FULL.toString());
							if(otherMessageItem!=null) {
								retChatMessage.setCkind(otherMessageItem.getCkind());
								retChatMessage.setCkindname(otherMessageItem.getCkindname());
								
								retChatMessage.setClabel(otherMessageItem.getClabel());
								retChatMessage.setClabelname(otherMessageItem.getClabelname());
							}
						}
					}else {
						if(UKDataContext.MediaTypeEnum.VOICE.toString().equals(otherMessage.getType())) {
							retChatMessage.setBustype(UKDataContext.MediaTypeEnum.VOICE.toString());
							otherMessage.setMsgtype(UKDataContext.MediaTypeEnum.VOICE.toString());
							retChatMessage.setDuration(otherMessage.getDuration());
						}
						if(StringUtils.isBlank(otherMessage.getScore()) && otherMessage.getItems()==null) {
							retChatMessage.setMatchtype(UKDataContext.AiMatchType.NO.toString());
						}else if(otherMessage.getItems()!=null) {
							retChatMessage.setMatchtype(UKDataContext.AiMatchType.SUGGEST.toString());
						}else {
							retChatMessage.setMatchtype(UKDataContext.AiMatchType.KW.toString());
						}
						retChatMessage.setCkind(otherMessage.getCkind());
						retChatMessage.setCkindname(otherMessage.getCkindname());
						
						retChatMessage.setClabel(otherMessage.getClabel());
						retChatMessage.setClabelname(otherMessage.getClabelname());
					}
					if(otherMessage.isTrans() && aiConfig!=null && aiConfig.isTransagent()) {
						retChatMessage.setQuickagent(true);
					}
					retChatMessage.setType(message.getType());
					/**
					 * 
					 * 外部机器人转接或者挂断操作的指令，只在 SmartIVR里使用 hungup/trans
					 */
					if(!StringUtils.isBlank(otherMessage.getType())) {
						retChatMessage.setBustype(otherMessage.getType());
					}
					
					if(!StringUtils.isBlank(otherMessage.getMessage())) {
						retChatMessage.setMessage(otherMessage.getMessage());	
					}else if(otherMessage.getItems()!=null && otherMessage.getItems().size() > 0 && aiConfig.isEnablesuggest()){
						retChatMessage.setMessage(aiConfig.getSuggestmsg());
					}
					if(otherMessage.getItems()!=null && otherMessage.getItems().size() > 0){
						if(aiConfig.isEnablesuggest() && !StringUtils.isBlank(aiConfig.getOthersuggestmsg())) {
							retChatMessage.setMessage(retChatMessage.getMessage() + aiConfig.getOthersuggestmsg());
						}
						retChatMessage.setSuggestmsg(objectMapper.writeValueAsString(otherMessage.getItems()));
					}
					
					retChatMessage.setTitle(otherMessage.getTitle());
					retChatMessage.setScore(otherMessage.getScore());
					retChatMessage.setMsgtype(otherMessage.getMsgtype());
					retChatMessage.setAppid(message.getAppid());
					retChatMessage.setUserid(aiUser.getUnikey());
					
					retChatMessage.setExpmsg(message.getMessage());
					
					retChatMessage.setTitle(otherMessage.getTitle());
					retChatMessage.setCode(otherMessage.getCode());
					
					retChatMessage.setQusid(message.getId());
					
					retChatMessage.setUsername("小E");
					retChatMessage.setChannel(message.getChannel());
					
					retChatMessage.setContextid(message.getContextid());
					retChatMessage.setOrgi(message.getOrgi());
					
					/**
					 * 命中结果，记录日志，记录DEBUG信息，下个版本增加功能
					 */
					retChatMessage.setTopic(true);
					retChatMessage.setTopicid(otherMessage.getId());
//					retChatMessage.setTopicatid(otherMessage.getCate());
					if(!StringUtils.isBlank(message.getMediaid())) {
						retChatMessage.setMatchtype(UKDataContext.AiMatchType.CLICK.toString());
					}else if(StringUtils.isBlank(retChatMessage.getMatchtype())){
						retChatMessage.setMatchtype(UKDataContext.AiMatchType.SUGGEST.toString());
					}else if(StringUtils.isBlank(retChatMessage.getMatchtype()) && !StringUtils.isBlank(otherMessage.getMatchtype())){
						retChatMessage.setMatchtype(otherMessage.getMatchtype());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retChatMessage;
	}

}
